﻿using ExtendNetease_DGJModule.MixMusicApi.M;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEST
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private List<SongInfoMix> DownloadsongInfoMixes = new List<SongInfoMix>();
        private List<TOPSongInfo> TOPSongInfoList = new List<TOPSongInfo>();
        //ExtendNetease_DGJModule.ExtendNeteaseModule ExtendNeteaseModule = new ExtendNetease_DGJModule.ExtendNeteaseModule();
        private void button1_Click(object sender, EventArgs e)
        {
          
            var keyword = this.textBox1.Text.Trim();
            var TOPSearch = ExtendNetease_DGJModule.MixMusicApi.API.TOPSearch(keyword);
            if (TOPSearch!=null)
            {
                this.richTextBox1.Text = JsonConvert.SerializeObject(TOPSearch);
            }
            //测试vip
            ExtendNetease_DGJModule.NeteaseMusic.SongInfo song = null;
            var v= ExtendNetease_DGJModule.NeteaseMusic.NeteaseMusicApi.SearchSongs(keyword, 10);
            v = v.Where(T => T.Duration.Ticks > 10000000*10).ToArray();
            if (keyword.Contains(" "))
            {
                var zz = keyword.Split(' ').Last();
                song = v.FirstOrDefault(T => T.ArtistNames==zz);
                if (song==null)
                {
                    song = v.FirstOrDefault(T => T.ArtistNames.Contains(zz));
                }
            }
            if (song==null)
            {
                foreach (var item in v)
                {
                    item.Similarity = ExtendNetease_DGJModule.MixMusicApi.API.Compute(item.Name, keyword);
                }
                //var v= ExtendNeteaseModule.Search
                var pxv = v.OrderBy(T => T.Similarity).ToList();

                song = pxv.FirstOrDefault();
            }
            
            if (song?.CanPlay == true)
            {
                this.richTextBox1.Text = JsonConvert.SerializeObject(song);
            }
            else
            {
                //Log($"{song.ArtistNames} - {song.Name} : 暂无版权喵");
                //没有版权调用第三方
                if (song!=null)
                {
                    keyword = song.Id.ToString();
                }
                var json = ExtendNetease_DGJModule.MixMusicApi.API.Search(keyword.Trim());
                if (!string.IsNullOrEmpty(json))
                {
                    JObject j = JObject.Parse(json);
                    if (j["result"].ToObject<int>() == 100)
                    {
                        SongInfoMix[] songsMix = j["data"]["list"].Select(K => new SongInfoMix(K)).ToArray();
                        var songMix = songsMix.FirstOrDefault();
                        //第三方歌先下载转换
                        if (!WebReady)
                        {
                            StartWebServer();
                        }
                        var DWjson = ExtendNetease_DGJModule.MixMusicApi.API.GetDownLoadUrl(songMix);
                        JObject DWj = JObject.Parse(DWjson);
                        if (DWj["result"].ToObject<int>() == 100)
                        {
                            var fit = DWj["data"][songMix.aId];
                            if (fit != null)
                            {
                                var url = fit["url"].ToString();
                                if (!string.IsNullOrEmpty(url))
                                {
                                    var ts = DateTimeOffset.Now.ToUnixTimeMilliseconds();

                                    var type = url.Split('?')[0].Split('.').Last();
                                    var savepath = Path.Combine(CacheFilePath, ts + "." + type);
                                    var mp3savepath = Path.Combine(CacheFilePath, ts + ".mp3");
                                    ExtendNetease_DGJModule.MixMusicApi.API.DownLoad(url, savepath);
                                    if (type.Contains("m4a"))
                                    {
                                        var ml = "-y -i \"" + savepath + "\" -ar 44100 -ac 2 -acodec mp3 \"" + mp3savepath + "\"";
                                        var pro = new System.Diagnostics.Process();
                                        pro.StartInfo.Arguments = ml;
                                        pro.StartInfo.FileName = CacheFFmpgePath;//要启动的程序外部名称  
                                        pro.StartInfo.CreateNoWindow = true;//不显示控制台窗口
                                        pro.StartInfo.UseShellExecute = true;//使用操作系统shell启动
                                        pro.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                                        pro.Start();
                                        //pro.BeginOutputReadLine();
                                        pro.WaitForExit();
                                        songMix.FilePath = mp3savepath;
                                        songMix.Url = LoclWebBaseUrl + ts + ".mp3";
                                    }
                                    else
                                    {
                                        songMix.FilePath = savepath;
                                        songMix.Url = LoclWebBaseUrl + ts + "." + type;
                                    }
                                    DownloadsongInfoMixes.Add(songMix);
                                }

                            }
                        }
                        this.richTextBox1.Text = JsonConvert.SerializeObject(songMix);
                    }
                }
            }
            
        }
        /// <summary>
        /// 启动http监听线程
        /// </summary>
        public static void StartWebServer()
        {

            //启动http监听线程
            CacheFilePath = Path.Combine(BaseEXEpath, @"DGJ_CacheFile");
            if (!Directory.Exists(CacheFilePath))
            {
                Directory.CreateDirectory(CacheFilePath);
            }
            var filePath = Path.Combine(CacheFilePath, "ffmpeg.exe");

            if (!File.Exists(filePath))
            {
                File.WriteAllBytes(filePath, Properties.Resources.ffmpeg);
            }
            CacheFFmpgePath = filePath;
            Application.ApplicationExit += new EventHandler(WebServer_Application_ApplicationExit);
          
            Task.Factory.StartNew(() => {

                var port = new Random().Next(49000, 59000);
                var localstring = "http://localhost:" + port + "/";

                LoclWebBaseUrl = localstring;
                hTTPServer = new ExtendNetease_DGJModule.HTTPServer(CacheFilePath, "localhost", port);
                hTTPServer.Start();
            });
            return;
        }
        private static ExtendNetease_DGJModule.HTTPServer hTTPServer = null;
        static void WebServer_Application_ApplicationExit(object sender, EventArgs e)
        {
            //do cleanup of your class
            if (hTTPServer!=null)
            {
                hTTPServer.Stop();
            }
        }
        private static string BaseEXEpath = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
        private static string CacheFilePath;
        private static bool WebReady = false;
        private static string CacheFFmpgePath;
        private static string LoclWebBaseUrl;
        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
